/**
 * 渲染进程入口文件
 * 负责初始化渲染进程，加载各个功能模块
 */

// 导入所需模块
const { ipcRenderer, ipcMain } = require('electron');
const systemMonitor = require('./system-monitor');
const quickApps = require('./quick-apps');
const uiComponents = require('./components/ui-components');
const waterReminder = require('./water-reminder');//水提醒js直接初始化，所以不用初始化
const clipboardManager = require('./clipboard-manager');
const countdown = require('./countdown');
const timeline = require('./timeline');
const taskManager = require('./task-manager');
const pomodoro = require('./pomodoro');
const networkSpeedMonitor = require('./network-speed');
const shutdown = require('./shutdown');
const other = require('./other');
const textFormat = require('./text-format');
const { showToast } = require('../common/show-toast');



// 初始化函数
function initialize() {
    console.log('渲染进程初始化...');

    // 设置菜单切换逻辑
    setupMenuNavigation();

    // 初始化各个功能模块-系统信息
    systemMonitor.initialize();
    // 初始化快捷应用
    quickApps.initialize();
    // 日历
    taskManager.initialize();
    // 倒计时
    countdown.initialize();

    // 设置侧边栏折叠功能
    setupSidebarCollapse();

    // 设置部分内容折叠功能
    setupSectionCollapse();
    // 初始化其他功能模块
    other.initialize();
    //检测配置文件
    //发送一个消息给主进程
    ipcRenderer.send('check-config');
    // 监听连接结果
    ipcRenderer.on('login-success', () => {
        console.time('网络连接耗时');
        showToast('网络连接成功', 'success');
        console.timeEnd('网络连接耗时');
    });
    // 监听来自主进程的 toast 消息
    ipcRenderer.on('show-toast', (event, { message, type }) => {
        showToast(message, type);
    });
    // 为功能卡片添加点击事件
    document.querySelectorAll('.view-all').forEach(card => {
        card.addEventListener('click', (e) => {
            e.preventDefault();
            const pageId = card.getAttribute('data-page');
            if (pageId) {
                // 切换页面
                document.querySelectorAll('.menu-item').forEach(i => i.classList.remove('active'));
                document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));

                // 激活对应菜单项
                document.querySelector(`.menu-item[data-page="${pageId}"]`).classList.add('active');

                // 显示对应页面
                document.getElementById(pageId).classList.add('active');
            }
            // 如果页面是日历,则初始化日历待办功能
            if (pageId === 'calendar') {
                taskManager.initialize();//初始化日历待办功能
            } else if (pageId === 'countdown') {
                countdown.initialize();//初始化倒计时
            }
        });
    });

    // 绑定快速添加待办事项按钮
    document.getElementById('quick-add-task')?.addEventListener('click', () => {
        const taskDate = document.getElementById('task-date');
        const taskForm = document.getElementById('task-form');
        const taskStartTime = document.getElementById('task-start-time');
        const taskEndTime = document.getElementById('task-end-time');
        const taskColor = document.getElementById('task-color');
        const taskCompleted = document.getElementById('task-completed');
        const taskModalTitle = document.getElementById('task-modal-title');
        const taskDeleteBtn = document.getElementById('task-delete-btn');
        const taskEditModal = document.getElementById('task-edit-modal');
        const dateStr = new Date().toISOString().split('T')[0];
        // 重置表单
        taskForm.reset();
        taskForm.dataset.taskId = '';

        // 设置默认值
        taskDate.value = dateStr;
        const now = new Date();
        taskStartTime.value = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
        now.setHours(now.getHours() + 1);
        taskEndTime.value = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
        taskColor.value = '#68a67d'; // 默认绿色
        taskCompleted.checked = false; // 默认未完成

        // 更新模态窗口标题和按钮
        taskModalTitle.textContent = '添加待办事项';
        taskDeleteBtn.style.display = 'none';
        currentTaskId = null;

        // 显示模态窗口
        taskEditModal.style.display = 'flex';
    });
    taskManager.updateTaskCount();

    console.log('渲染进程初始化完成');
}

// 菜单切换逻辑
function setupMenuNavigation() {
    document.querySelectorAll('.menu-item').forEach(item => {
        item.addEventListener('click', () => {
            console.log('点击了菜单项:', item.getAttribute('data-page'));
            document.querySelectorAll('.menu-item').forEach(i => i.classList.remove('active'));
            document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));

            item.classList.add('active');
            const pageId = item.getAttribute('data-page');
            document.getElementById(pageId).classList.add('active');
            if (pageId === 'system-monitor') {//系统监控
                // systemMonitor.initialize();
            } else if (pageId === 'pomodoro') {//番茄时钟
                pomodoro.initPomodoro();
            } else if (pageId === 'quick-apps') {//快捷应用
                quickApps.initialize();
            } else if (pageId === 'ui-components') {//UI组件
                uiComponents.initialize();
            } else if (pageId === 'water') {//水提醒
                //文件里面已经初始化了
            } else if (pageId === 'clipboard') {//剪贴板管理
                clipboardManager.initialize();
            } else if (pageId === 'countdown') {//未来倒计时
                // countdown.initialize();
            } else if (pageId === 'timeline') {//时间轴
                timeline.initialize();
            } else if (pageId === 'calendar') {//日历  
                // // 日历
                taskManager.initialize();
            } else if (pageId === 'network-speed') {//网速监控
                //网速监控
                networkSpeedMonitor.initialize();
            } else if (pageId === 'shutdown') {//关机
                //关机
                shutdown.initialize();
            } else if (pageId === 'other') {//设置
                //设置
                other.initialize();
            }else if (pageId === 'text-format') {//文本格式化
                //文本格式化
                textFormat.initialize();
            }
        });
    });
}

// 设置部分内容折叠功能
function setupSectionCollapse() {
    document.querySelectorAll('.section-header').forEach(header => {
        header.addEventListener('click', () => {
            const sectionId = header.getAttribute('data-section');
            const content = document.getElementById(`${sectionId}-content`);
            const icon = header.querySelector('.fas.fa-chevron-down');
            if (content != null) {

                content.classList.toggle('expanded');
                if (content.classList.contains('expanded')) {
                    icon.style.transform = 'rotate(0deg)';
                } else {
                    icon.style.transform = 'rotate(-90deg)';
                }
            }
        });
    });

    // 初始化折叠图标状态
    document.querySelectorAll('.section-header').forEach(header => {
        const sectionId = header.getAttribute('data-section');
        const content = document.getElementById(`${sectionId}-content`);
        const icon = header.querySelector('.fas.fa-chevron-down');

        if (content && !content.classList.contains('expanded')) {
            icon.style.transform = 'rotate(-90deg)';
        }
    });
}
// 设置侧边栏折叠功能
function setupSidebarCollapse() {
    // console.info('setupSidebarCollapse');
    const sidebar = document.querySelector('.sidebar');
    const toggleBtn = document.querySelector('.toggle-sidebar');

    toggleBtn.addEventListener('click', () => {
        sidebar.classList.toggle('collapsed');
    });
}

// 导出模块
module.exports = {
    initialize,
    showToast
};

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM加载完成，开始初始化渲染进程...');
    initialize();
});